package com.wxy.xr.servlet;


import com.wxy.xr.bean.Award;
import com.wxy.xr.bean.UploadParams;
import com.wxy.xr.util.Uploads;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@WebServlet("/award/*")
public class AwardServlet extends BaseServlet<Award>{
    public  void admin(HttpServletRequest request, HttpServletResponse response) throws Exception{
        request.setAttribute("awards",service.list());
        forward(request, response,"admin/award.jsp");
    }

    public  void save(HttpServletRequest request, HttpServletResponse response) throws Exception{
        UploadParams uploadParams = Uploads.parseRequest(request);

         Award award=new Award();
        BeanUtils.populate(award,uploadParams.getParams());
        if(award.getImage()!=null&&award.getImage().length()==0){
            award.setImage(null);
        }
        FileItem item=uploadParams.getFileParam("imageFile");
        award.setImage(Uploads.uploadImage(item,request,award.getImage()));

        if(service.save(award)){
            redirect(request, response,"award/admin");
        }else{
            forward(request, response,"获奖信息保存失败");}
    }

    public  void remove(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String[] idstrs=request.getParameterValues("id");
        List<Integer> ids=new ArrayList<>();
        for(String idstr:idstrs){
            ids.add(Integer.valueOf(idstr));
        }
        if(service.remove(ids)){
            redirect(request, response,"award/admin");
        }else{
            forward(request, response,"获奖信息删除失败");}
    }
}
